<template>
  <a-modal
    :visible="myVisible"
    @ok="handleOk"
    @cancel="handleCancel"
    okText="立即发送"
  >
    <template #title> 分享 </template>
    <div>
      <!-- <a-input v-model="selectedModelMsg" style="height: 40px" allow-clear> -->
      <div style="display: flex">
        <a-input-tag
          v-model="selectedMsg"
          :field-names="{
            label: 'name'
          }"
          :max-tag-count="3"
          :style="{ width: '320px' }"
          placeholder="Please Enter"
          allow-clear
        >
          <template #suffix>
            <icon-font
              type="icon-a-10xuanzelianxiren"
              :size="18"
              :style="{
                cursor: 'pointer'
              }"
              @click="goSelectPersonnel"
          /></template>
        </a-input-tag>
      </div>
    </div>
    <template #footer>
      <div style="width: 100%; display: flex; justify-content: space-between">
        <a-space
          ><span>分享方式</span
          ><a-link
            ><a-space><icon-send /><span>聊天</span></a-space></a-link
          ><span>|</span>
          <a-tooltip content="复制链接" position="bottom">
            <a-button type="text" class="iconColor">
              <template #icon>
                <icon-font
                  type="icon-lianjie"
                  :size="18"
                  :style="{
                    cursor: 'pointer'
                  }"
                  @click="copy()"
                />
              </template>
            </a-button>
          </a-tooltip>
          <a-tooltip content="分享二维码" position="bottom">
            <a-button type="text" class="iconColor">
              <template #icon>
                <icon-font
                  type="icon-erweima"
                  :size="18"
                  :style="{
                    cursor: 'pointer'
                  }"
                  @click="copy()"
                />
              </template>
            </a-button> </a-tooltip></a-space
        ><a-space
          ><a-button type="outline" @click="handleCancel">取消</a-button
          ><a-button type="primary" @click="sendMsg"
            >立即发送</a-button
          ></a-space
        >
      </div>
    </template>
  </a-modal>

  <a-modal
    :visible="modelVisible"
    @ok="SelectOk"
    @cancel="modelCancel"
    :hide-title="true"
    :width="800"
  >
    <div class="wrap">
      <div class="left-content">
        <div class="search">
          <!-- <a-input-search placeholder="Please enter something" /> -->
        </div>
        <div class="iconBox" v-show="!isShow">
          <a-tooltip content="最近聊天" position="bottom">
            <a-button type="text" class="iconColor">
              <template #icon>
                <icon-font
                  type="icon-liaotian"
                  :size="26"
                  :style="{
                    cursor: 'pointer'
                  }"
                  @click="setListType(1)"
                />
              </template>
            </a-button>
          </a-tooltip>
          <a-tooltip content="按群聊选" position="bottom">
            <a-button type="text" class="iconColor">
              <template #icon>
                <icon-font
                  type="icon-qunliao"
                  :size="19"
                  :style="{
                    cursor: 'pointer'
                  }"
                  @click="setListType(2)"
                />
              </template>
            </a-button>
          </a-tooltip>
          <a-tooltip content="按架构选" position="bottom">
            <a-button type="text" class="iconColor">
              <template #icon>
                <icon-font
                  type="icon-zuzhijiagou"
                  :size="19"
                  :style="{
                    cursor: 'pointer'
                  }"
                  @click="setListType(2)"
                />
              </template>
            </a-button>
          </a-tooltip>
        </div>
        <!-- <a-divider /> -->
        <RecentChatHistory
          v-show="isShow && listType === 1"
          v-model:visible="isShow"
          v-model:checkboxDataList="RecentChatData"
          v-model:checkbox-key="RecentChatKey"
        />
        <groupChat
          v-show="isShow && listType === 2"
          v-model:visible="isShow"
          v-model:checkbox-data-list="groupChatData"
          v-model:checkbox-key="groupChatKey"
        />
      </div>
      <div class="right-content">
        <div style="font-weight: bold">已选择（{{ selectedMsg.length }}）</div>
        <a-space style="margin-top: 5px; flex-wrap: wrap"
          ><a-tag
            size="large"
            v-for="(item, index) in selectedMsg"
            :key="item.id"
            closable
            style="margin-top: 5px"
            @close="chatClose($event, item)"
            ><a-space v-if="item.listType === 1">
              <PersonnelIcon
                :backgroundColor="isColor(index)"
                :name="item.name"
                :headPortraits="item.headPortrait"
              />
              <div>
                {{ item.name }}
              </div></a-space
            ><a-space v-if="item.listType === 2">
              <PersonnelIcon
                :backgroundColor="isColor(index)"
                :name="item.name"
                :headPortraits="item.headPortrait[0]"
              />
              <div>
                {{ item.name }}
              </div></a-space
            ></a-tag
          ></a-space
        >
      </div>
    </div>
  </a-modal>
</template>
<script setup lang="ts">
import { GetHumanRosterList } from '@/apis/management/human/humanRoster';
import RecentChatHistory from './RecentChatHistory.vue';
import groupChat from './groupChat.vue';
import {
  contactGroupCreate,
  getContactGroupList,
  getFrequentContact,
  editLabel,
  getLabeList,
  getFriendList
} from '@/apis/client/addressBook/index';
import { Message } from '@arco-design/web-vue';
import useClipboard from 'vue-clipboard3';
import PersonnelIcon from './PersonnelIcon.vue';
import webSocket from '@/hooks/webSocket';
import { cloneDeep } from 'lodash';

const props = withDefaults(
  defineProps<{
    visible: boolean;
    sharingInfo: any;
  }>(),
  {
    visible: false
  }
);
const selectedMsg = ref<any>([]);
const RecentChatData = ref<any>([]);
const RecentChatKey = ref<any>([]);
const groupChatData = ref<any>([]);
const groupChatKey = ref<any>([]);
const myVisible = computed({
  get: () => props.visible,
  set: () => emit('update:visible')
});
const emit = defineEmits(['update:visible']);
const listType = ref<any>(1);
const close = () => {
  emit('update:visible', false);
};

const handleCancel = () => {
  close();
};
const modelVisible = ref(false);
const goSelectPersonnel = () => {
  modelVisible.value = true;
};
const color = ['#0089ff', '#cdf5b0', '#ffe2da'];
const isColor = (index: number) => {
  if (index <= color.length - 1) {
    return color[index];
  } else {
    return color[(index + 1) % color.length];
  }
};
const isShow = ref(false);
const setListType = (key: number) => {
  listType.value = key;
  isShow.value = true;
};

watchEffect(() => {
  if (isShow.value && (RecentChatData.value || groupChatData.value)) {
    const newMsg: any = [];
    selectedMsg.value = newMsg.concat(
      RecentChatData.value,
      groupChatData.value
    );
    console.log('res', selectedMsg.value);
  }
});
// const selectedModelMsg = ref<any>([]);
// watchEffect(() => {
//   if (selectedMsg.value) {
//     // selectedMsg.value.map((ele=>ele.name||ele.listenUser));
//     selectedMsg.value.forEach((ele: any) => {
//       if (ele.listenUser) selectedModelMsg.value.push(ele.listenUser?.name);
//       if (ele.groupInfo) selectedModelMsg.value.push(ele.groupInfo?.name);
//       if (ele.name) selectedModelMsg.value.push(ele.name);
//     });
//   }
// });

const { toClipboard } = useClipboard();
const copy = async () => {
  try {
    await toClipboard(sharingInfo.value.downloadPath);
    Message.success('复制成功');
  } catch (err: unknown) {
    console.log(err);
  }
};

const SelectOk = () => {
  modelVisible.value = false;
};

const modelCancel = () => {
  modelVisible.value = false;
};
function formatFileSize(size: number) {
  if (size < 1024) {
    return size + ' B';
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(2) + ' KB';
  } else {
    return (size / (1024 * 1024)).toFixed(2) + ' MB';
  }
}
const ws = ref();
const sharingInfo = ref();
const { connect, receiveMsg } = webSocket();
onMounted(() => {
  sharingInfo.value = cloneDeep(props.sharingInfo);
  console.log(props.sharingInfo);
  sharingInfo.value.fileSize = formatFileSize(sharingInfo.value.fileSize);
  ws.value = connect();
});

const sendMsg = () => {
  if (!selectedMsg.value) {
    Message.success('请选择分享对象');
    return;
  }
  selectedMsg.value.forEach((item) => {
    if (item.listType === 1) {
      if (item.listenUserId) {
        let msg: any = {
          listenUserId: item.listenUserId,
          content: {
            url: sharingInfo.value.downloadPath,
            name: sharingInfo.value.useFileName,
            size: sharingInfo.value.fileSize
          },
          type: 4,
          groupId: 0
        };
        msg.content = JSON.stringify(msg.content);
        ws.value.send(JSON.stringify(msg));
      }
      if (item.groupInfoId) {
        let msg: any = {
          listenUserId: 0,
          content: {
            url: sharingInfo.value.downloadPath,
            name: sharingInfo.value.useFileName,
            size: sharingInfo.value.fileSize
          },
          type: 4,
          groupId: item.groupInfoId
        };
        msg.content = JSON.stringify(msg.content);
        ws.value.send(JSON.stringify(msg));
      }
    } else if (item.listType === 2) {
      let msg: any = {
        listenUserId: 0,
        content: {
          url: sharingInfo.value.downloadPath,
          name: sharingInfo.value.useFileName,
          size: sharingInfo.value.fileSize
        },
        type: 4,
        groupId: item.id
      };
      msg.content = JSON.stringify(msg.content);
      ws.value.send(JSON.stringify(msg));
    }
  });
};
</script>

<style scoped>
:deep(.arco-input-outer),
:deep(.arco-input-append) {
  border-left: 1px solid #fff;
  border: 1px solid var(--color-neutral-4);
}

.wrap {
  display: flex;
}

.left-content {
  width: 50%;
  padding-right: 10px;
  border-right: 1px solid var(--color-neutral-4);
  .iconBox {
    padding: 10px;
    display: flex;
    justify-content: space-around;
  }
}
.right-content {
  width: 50%;
  margin: 10px;
}

/* :deep(.arco-divider),
:deep(.arco-divider-horizontal) {
  margin: 5px 0;
} */
</style>
